//
//  AppDelegate.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/14.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "AppDelegate.h"
#import "JKTopWindowViewController.h"
#import "LaunchImageViewController.h"
#import "SQLiteManager.h"
#import "WXApi.h"
#import "JKProgressHUD.h"
#import <WeiboSDK.h>
#import "MainViewController.h"

#import <UMAnalytics/MobClick.h>
#import <UMCommon/UMCommon.h>

// 以下仅供测试使用
//#import "NSObject+Property.h"
//#import "NetworkingTool.h"
//#import "JKDateTool.h"

@interface AppDelegate () <WXApiDelegate, WeiboSDKDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 
    // 注册微信
    [WXApi registerApp:JKWXAppkey];
    
    //微博SDK
//    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:JKWeiboAppKey];
    
    [self setupUM];
    
    [self setupUserDefaults];
    
    self.window = [[UIWindow alloc] init];
    self.window.frame = [UIScreen mainScreen].bounds;
    
    //MainViewController *mainVc = [[MainViewController alloc] init];
    //self.window.rootViewController = mainVc;
    
    LaunchImageViewController *launchVc = [[LaunchImageViewController alloc] init];
    
    self.window.rootViewController = launchVc;
    
    [self.window makeKeyAndVisible];
    
    // 打开数据库
    [[SQLiteManager sharedmanager] openDB:@"story.sqlite"];
    
    // 程序启动后，判断是否有超过7天的数据，如果有，则删除
    [SQLiteManager clearData];
    
    // 增加3DTouch启动程序时的处理
    // 从启动项中获取是否是从3DTouch中启动的
    UIApplicationShortcutItem *item = launchOptions[UIApplicationLaunchOptionsShortcutItemKey];
    
    if (item) {
        // 说明是使用3DTouch启动的,那么当页面启动的时候就需要直接跳转到新闻详细中
        // 在启动的时候设置一个标志,是否需要跳转,然后在LaunchImageViewController中会判断是否有这个标志.如果有就进行界面的跳转
        launchVc.jumpTo = [item.type isEqualToString:@"1"] ? @"最新日报" : @"最新瞎扯";
    }
    
    [self add3DTouch];
    
    return YES;
}

- (void)setupUM{
    [UMConfigure initWithAppkey:JKUMAnalyticsAppkey channel:@"Web"];
//    UMConfigInstance.appKey = @"xxxxxxxxxxxxxx...";
//    UMConfigInstance.ChannelId = @"App Store";
//    UMConfigInstance.eSType = E_UM_GAME; //仅适用于游戏场景，应用统计不用设置
//    …
//    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
}

- (void)add3DTouch{
    
    UIApplicationShortcutIcon *icon1 = [UIApplicationShortcutIcon iconWithType:(UIApplicationShortcutIconTypeShare)];
    
    UIApplicationShortcutItem *item1 = [[UIApplicationShortcutItem alloc] initWithType:@"1" localizedTitle:@"最新日报" localizedSubtitle:nil icon:icon1 userInfo:nil];
    
    UIApplicationShortcutIcon *icon2 = [UIApplicationShortcutIcon iconWithType:(UIApplicationShortcutIconTypeCompose)];
    UIApplicationShortcutItem *item2 = [[UIApplicationShortcutItem alloc] initWithType:@"2" localizedTitle:@"最新瞎扯" localizedSubtitle:nil icon:icon2 userInfo:nil];
    
    [UIApplication sharedApplication].shortcutItems = @[item1,item2];
}

#pragma mark - 3D Touch的操作
- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler{
    
    if ([application.keyWindow.rootViewController isKindOfClass:[LaunchImageViewController class]]) {
        
        [(LaunchImageViewController *)application.keyWindow.rootViewController setJumpTo:[shortcutItem.type isEqualToString:@"1"] ? @"最新日报" : @"最新瞎扯"];
        
    }else if ([application.keyWindow.rootViewController isKindOfClass:[MainViewController class]]){
        
        [(MainViewController *)application.keyWindow.rootViewController setJumpTo:[shortcutItem.type isEqualToString:@"1"] ? @"最新日报" : @"最新瞎扯"];
    }
    
    completionHandler(YES);
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self] || [WeiboSDK handleOpenURL:url delegate:self];//|| [TencentOAuth HandleOpenURL:url]
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return [WXApi handleOpenURL:url delegate:self] || [WeiboSDK handleOpenURL:url delegate:self];//|| [TencentOAuth HandleOpenURL:url]
}

-(void)setupUserDefaults {
    NSString *currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    if (currentSkinModel==nil) {
        [[NSUserDefaults standardUserDefaults] setObject:JKDaySkinModelValue forKey:JKCurrentSkinModelKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    BOOL isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:JKIsLoginKey];
    if (!isLogin) {
        [[NSUserDefaults standardUserDefaults] setObject:@"未登录" forKey:JKUserNameKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // 添加一个window，点击这个window，可以让屏幕的scrollView滚动到最顶部
//    [JKTopWindowViewController show];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - <WXApiDelegate>
-(void) onResp:(BaseResp*)resp;{
    switch (resp.errCode) {
        case WXSuccess:
            [JKProgressHUD showSuccessWithStatus:@"分享成功！"];
            break;
        case WXErrCodeUserCancel:
            [JKProgressHUD showErrorWithStatus:@"取消操作！"];
            break;
        case WXErrCodeAuthDeny:
            [JKProgressHUD showErrorWithStatus:@"授权失败！"];
            break;
        case WXErrCodeUnsupport:
            [JKProgressHUD showErrorWithStatus:@"微信不支持！"];
            break;
        default:
            [JKProgressHUD showErrorWithStatus:@"分享失败！"];
            break;
    }
}

#pragma mark - <WeiboSDKDelegate>
/**
 收到一个来自微博客户端程序的请求
 
 收到微博的请求后，第三方应用应该按照请求类型进行处理，处理完后必须通过 [WeiboSDK sendResponse:] 将结果回传给微博
 @param request 具体的请求对象
 */
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request{
}

/**
 收到一个来自微博客户端程序的响应
 
 收到微博的响应后，第三方应用可以通过响应类型、响应的数据和 WBBaseResponse.userInfo 中的数据完成自己的功能
 @param response 具体的响应对象
 */
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response{
    
    switch (response.statusCode) {
        case WeiboSDKResponseStatusCodeSuccess:
            [JKProgressHUD showSuccessWithStatus:@"分享成功！"];
            break;
        case WeiboSDKResponseStatusCodeUserCancel:
            [JKProgressHUD showErrorWithStatus:@"取消操作！"];
            break;
        case WeiboSDKResponseStatusCodeAuthDeny:
            [JKProgressHUD showErrorWithStatus:@"授权失败！"];
            break;
        case WeiboSDKResponseStatusCodeUnsupport:
            [JKProgressHUD showErrorWithStatus:@"不支持的请求！"];
            break;
        case WeiboSDKResponseStatusCodeUnknown:
            [JKProgressHUD showErrorWithStatus:@"未知错误！"];
            break;
        case WeiboSDKResponseStatusCodePayFail:
            [JKProgressHUD showErrorWithStatus:@"支付失败！"];
            break;
        default:
            [JKProgressHUD showErrorWithStatus:@"分享失败！"];
            break;
    }
}
@end
